package com.caoJun.jdbc;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @Description: 对数据库进行修改操作
 * @Author 83-start
 * @Time 2021/4/20 15:57
 */
public class JdbcUpdate {
    // 数据库链接对象
    private Connection connection;

    // 初始化链接数据库
    public JdbcUpdate() {
        connection = new JdbcTools().connection;
    }

    /**
     * 查询用户的余额
     *
     * @param id
     * @return
     */
    public double selectUserBalance(int id) {
        double balance = 0;
        ResultSet rs = null;

        try {
            // 定义查询语句
            PreparedStatement ps = connection.prepareStatement("SELECT balance FROM account WHERE id = ?");
            ps.setInt(1, id);

            rs = ps.executeQuery();

            if (rs.next()) {
                balance = rs.getDouble(1);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return balance;
    }

    /**
     * 转账操作
     *
     * @param user1   转账人
     * @param user2   收账人
     * @param balance
     */
    public void transferAccounts(int user1, int user2, double balance){
        double user1Balance = this.selectUserBalance(user1);
        System.out.println("1=============" + user1Balance);
        double user2Balance = this.selectUserBalance(user2);
        System.out.println("2=============" + user2Balance);

        // 定义参数
        String updateSql = "UPDATE account SET balance = ? WHERE id= ?";
        try {
            PreparedStatement user1Ps = connection.prepareStatement(updateSql);
            user1Ps.setDouble(1, user1Balance - balance);
            user1Ps.setInt(2, user1);

            PreparedStatement user2Ps = connection.prepareStatement(updateSql);
            user2Ps.setDouble(1, user2Balance + balance);
            user2Ps.setInt(2, user2);

            // 执行代码
            int user1Ex = user1Ps.executeUpdate();
            int user2Ex = user2Ps.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
